﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Infrastructure.CustomException;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;
using QMERP.Infrastructure.Extensions;

namespace QMERP.Application.Services
{
    public class CurrencyService : ICurrencyService
    {
        private readonly IMapper _mapper;
        private readonly QMERPDbContext _db;
        public CurrencyService(IMapper mapper, QMERPDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取币种列表基础数据
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task<List<CurrencyResponse>> GetBasicCurrencies()
        {
            var list = await _db.Currency.GetAll().ToListAsync();
            return _mapper.Map<List<CurrencyResponse>>(list);
        }
        /// <summary>
        /// 币种窗体
        /// </summary>
        /// <returns></returns>
        public async Task<PageResponse<CurrencyResponse>> Query(PageRequest<CurrencyRequest> request)
        {
            var response = new PageResponse<CurrencyResponse>();
            var query = Where(request);
            var list = await query.Paging(request.PageIndex, request.PageSize).ToListAsync();
            var currencyResponse = _mapper.Map<List<CurrencyResponse>>(list);
            response.TotalCount = await query.CountAsync();
            response.PageIndex = request.PageIndex;
            response.PageSize = request.PageSize;
            response.List = currencyResponse;
            return response;
        }
        /// <summary>
        /// 获取id的币种详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<CurrencyResponse> Detail(long id)
        {
            var model = await _db.Currency.GetAll().FindByIdAsync(id);
            return _mapper.Map<CurrencyResponse>(model);
        }
        /// <summary>
        /// 币种保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(CurrencySaveRequest request)
        {
            if (await _db.Currency.GetAll().AnyAsync(x => x.Code.ToLower() == request.Code && x.Id != request.Id))
                throw new ApiException("币种代码已存在!");
            if (await _db.Currency.GetAll().AnyAsync(x => x.Name.ToLower() == request.Name && x.Id != request.Id ))
                throw new ApiException("币种名称已存在!");
            if (request.Id == null)
            {
                Currency model = _mapper.Map<Currency>(request);
                await _db.Currency.AddAsync(model);
            }
            else
            {
                Currency? model = await _db.Currency.GetAll().FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("币种不存在!");
                model.Code = request.Code;
                model.Name = request.Name;
                model.Symbol = request.Symbol;
                model.AcceptRate = request.AcceptRate;
                model.AdjustRate = request.AdjustRate;
                model.Standard = request.Standard;
                model.IsEnable = request.IsEnable;
            }
            await _db.SaveChangesAsync();
        }

        private IQueryable<Currency> Where(PageRequest<CurrencyRequest> request)
        {
            IQueryable<Currency> query = _db.Currency.GetAll();
            if (!request.Query.Code.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Code.Contains(request.Query.Code!));
            }
            if (!request.Query.Name.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Name!));
            }
            return query.OrderByDescending(x=>x.CreatedOn);
        }
    }
}
